package org.stone.project.ncCheck.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.stone.project.ncCheck.domain.HistoryIp;
import org.stone.project.ncCheck.service.HistoryIpService;
import org.stone.project.ncCheck.service.UserInfoService;
import org.stone.project.ncCheck.utils.IpUtil;

import java.net.SocketException;
import java.util.ArrayList;
import java.util.Date;

@Slf4j
@Component
public class IpTask {
    @Autowired
    private IpUtil ipUtil;

    @Autowired
    private HistoryIpService historyIpService;

    @Autowired
    private UserInfoService userInfoService;

    @Scheduled(fixedDelay = 600000)
    public void ipCheck() throws SocketException {
        boolean notifitionFlag = false;
        log.info("ip检查任务开始");
        ArrayList<String> ipv4List = new ArrayList<>();
        ArrayList<String> ipv6List = new ArrayList<>();
        String ipv4 = "";
        String ipv6 = "";
        ipUtil.addAddress(ipv4List,ipv6List);
        HistoryIp lastRecord = historyIpService.findLastRecord();
        if (CollectionUtil.isNotEmpty(ipv4List)) {
            ipv4 = ipv4List.get(0);
        }
        if (CollectionUtil.isNotEmpty(ipv6List)) {
            ipv6 = ipv6List.get(0);
        }

        if (ObjectUtil.isNotNull(lastRecord)){
            if (!(ipv4.equals(lastRecord.getIpv4()) && ipv6.equals(lastRecord.getIpv6()))){
                HistoryIp historyIp = new HistoryIp();
                historyIp.setIpv4(ipv4);
                historyIp.setIpv6(ipv6);
                historyIp.setCreateTime(new Date());
                historyIpService.save(historyIp);
                notifitionFlag = true;
                lastRecord = historyIp;
            }else {
                log.info("ip未变");
            }
        }else {
            if (ipv4 != "" || ipv6 != ""){
                HistoryIp historyIp = new HistoryIp();
                historyIp.setIpv4(ipv4);
                historyIp.setIpv6(ipv6);
                historyIp.setCreateTime(new Date());
                historyIpService.save(historyIp);
                lastRecord = historyIp;
                notifitionFlag = true;
            }else {
                log.info("历史记录不存在，当前ip不存在");
            }
        }

        if (notifitionFlag){
            userInfoService.sendAllMsg("新机器ipv4地址为"+lastRecord.getIpv4()+"，ipv6地址为"+lastRecord.getIpv6());
        }
        log.info("ip检查任务结束");
    }
}
